/*
 * Copyright (c) [2020-2021] [http://www.zxpnet.com]
 */

package com.zxp.springboot.config;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.beetl.core.Context;
import org.beetl.core.Function;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.core.env.Environment;

import java.io.UnsupportedEncodingException;

/**
 * beetl拓展配置,绑定一些工具类,方便在模板中直接调用
 * @author zxp
 * @date 2021/6/21 16:54
 */
@RequiredArgsConstructor
public class CustomBeetlGroupUtilConfiguration extends BeetlGroupUtilConfiguration {

    private final Environment env;

    @Override
    public void initOther() {

        // 获取当前用户的接口
        //groupTemplate.registerFunctionPackage("loginUser", loginUserApi);

        // 对象工具类
        groupTemplate.registerFunctionPackage("objectUtil", ObjectUtil.class);

        // 获取基本信息的工具
        //groupTemplate.registerFunctionPackage("constants", SystemConfigExpander.class);

        // 多语言
        //groupTemplate.registerFunctionPackage("translate", QuickTranslateUtil.class);

        // 下拉选字典
        //groupTemplate.registerTag("dict_select", SysDictSelectTag.class);

        // 单选字典
        //groupTemplate.registerTag("dict_radio", SysDictRadioTag.class);

        // 多选字典
        //groupTemplate.registerTag("dict_checkbox", SysDictCheckBoxTag.class);

        groupTemplate.registerFunctionPackage("uuid", UUID.class);
        groupTemplate.registerFunctionPackage("strUtil", StrUtil.class);

        groupTemplate.registerFunction("env", new Function() {
            @Override
            public String call(Object[] paras, Context ctx) {
                String key = (String)paras[0];
                String value =  env.getProperty(key);
                if(value!=null) {
                    return getStr(value);
                }
                if(paras.length==2) {
                    return (String)paras[1];
                }
                return null;
            }

            protected String getStr(String str) {
                try {
                    return new String(str.getBytes("iso8859-1"),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }
}
